// API服务文件，用于与后端通信
import axios from 'axios'
import { useUserStore } from '@/stores/user'

// 创建axios实例
const api = axios.create({
  baseURL: '/api', // 使用代理
  timeout: 300000, // 30秒超时
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 添加认证token
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('响应错误:', error)
    if (error.response) {
      // 服务器返回了错误状态码
      console.error('错误状态码:', error.response.status)
      console.error('错误信息:', error.response.data)
      
      // 处理401认证错误
      if (error.response.status === 401) {
        const userStore = useUserStore()
        userStore.logout()
        // 重定向到登录页面
        if (window.location.pathname !== '/login') {
          window.location.href = '/#/login'
        }
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.error('网络错误或服务器无响应')
    } else {
      // 其他错误
      console.error('请求配置错误:', error.message)
    }
    return Promise.reject(error)
  }
)

// API接口
export const apiService = {
  // 发送消息并获取流式回答
  async sendMessage(question, conversationId = null) {
    const response = await api.post('/stream-question', {
      question: question,
      conversation_id: conversationId
    })
    return response
  },

  // 获取可用模型列表（可选：按类型过滤）
  async getModels(modelType = null) {
    const params = modelType ? { model_type: modelType } : {}
    const response = await api.get('/models', { params })
    return response
  },

  // 获取嵌入模型列表
  async getEmbeddingModels() {
    return await api.get('/models', { params: { model_type: 'embedding' } })
  },

  // 获取会话列表
  async getConversations() {
    const response = await api.get('/conversations')
    return response
  },

  // 获取单个会话详情
  async getConversation(conversationId) {
    const response = await api.get(`/conversations/${conversationId}`)
    return response
  },

  // 获取会话的所有消息
  async getConversationMessages(conversationId) {
    const response = await api.get(`/conversations/${conversationId}/messages`)
    return response
  },

  // 删除会话（RESTful路径参数）
  async deleteConversation(conversationId) {
    const res = await api.delete(`/conversations/${conversationId}`)
    return res
  },

  // 更新会话标题
  async updateConversationTitle(conversationId, title) {
    const res = await api.post(`/conversations/${conversationId}/title`, null, {
      params: { title }
    })
    return res
  },

  // 取消生成任务
  async cancelGeneration(conversationId) {
    if (!conversationId && conversationId !== 0) return { success: true }
    const res = await api.post(`/conversations/${conversationId}/cancel`)
    return res
  },

  // 知识库：创建
  async createKnowledgeBase(payload) {
    return await api.post('/knowledge-bases', payload)
  },

  // 知识库：列表
  async listKnowledgeBases(page = 1, pageSize = 10) {
    return await api.get('/knowledge-bases', { params: { page, page_size: pageSize } })
  },

  // 知识库：详情
  async getKnowledgeBase(kbId) {
    return await api.get(`/knowledge-bases/${kbId}`)
  },

  // 知识库：更新
  async updateKnowledgeBase(kbId, payload) {
    return await api.patch(`/knowledge-bases/${kbId}`, payload)
  },

  // 知识库：删除
  async deleteKnowledgeBase(kbId) {
    return await api.delete(`/knowledge-bases/${kbId}`)
  },

  // 知识库：相似度召回
  async searchKnowledge(kbId, query, topK = 8) {
    return await api.get(`/knowledge-bases/${kbId}/recall`, { params: { q: query, top_k: topK } })
  },

  // 知识库：召回历史
  async listRecallHistory(kbId, limit = 20) {
    return await api.get(`/knowledge-bases/${kbId}/recall/history`, { params: { limit } })
  },

  // 知识库：删除召回历史
  async deleteRecallHistory(kbId, historyId) {
    return await api.delete(`/knowledge-bases/${kbId}/recall/history/${historyId}`)
  },

  // 提示词库：创建
  async createSystemPrompt(title, content, enableContext = false, contextPlaceholder = '[CONTEXT]') {
    return await api.post('/system-prompts', { title, content, enable_context: enableContext, context_placeholder: contextPlaceholder })
  },

  // 提示词库：列表
  async listSystemPrompts(page = 1, pageSize = 12) {
    return await api.get('/system-prompts', { params: { page, page_size: pageSize } })
  },

  // 提示词库：详情
  async getSystemPrompt(id) {
    return await api.get(`/system-prompts/${id}`)
  },

  // 提示词库：更新
  async updateSystemPrompt(id, title, content, enableContext = undefined, contextPlaceholder = undefined) {
    const payload = { }
    if (typeof title !== 'undefined') payload.title = title
    if (typeof content !== 'undefined') payload.content = content
    if (typeof enableContext !== 'undefined') payload.enable_context = enableContext
    if (typeof contextPlaceholder !== 'undefined') payload.context_placeholder = contextPlaceholder
    return await api.patch(`/system-prompts/${id}`, payload)
  },

  // 提示词库：删除
  async deleteSystemPrompt(id) {
    return await api.delete(`/system-prompts/${id}`)
  },

  // 文档：按知识库分页列表
  async listDocumentsByKb(kbId, page = 1, pageSize = 10) {
    return await api.get('/knowledge-bases/' + kbId + '/documents', { params: { page, page_size: pageSize } })
  },

  // 文档：批量上传（上传即处理分块+嵌入）
  async uploadDocuments(kbId, files, options = {}) {
    const formData = new FormData()
    for (const f of files) {
      formData.append('files', f)
    }

    const params = new URLSearchParams()
    if (kbId) params.append('kb_id', kbId)
    if (options.embeddingModelName) params.append('embedding_model_name', options.embeddingModelName)
    if (options.chunkMode) params.append('chunk_mode', options.chunkMode)
    if (options.chunkMode === 'delimiter' && options.delimiter) params.append('chunk_delimiter', options.delimiter)
    if (options.chunkMode === 'length' && options.chunkSize) params.append('chunk_size', options.chunkSize)
    if (options.chunkMode === 'length' && (options.chunkOverlap || options.chunkOverlap === 0)) params.append('chunk_overlap', options.chunkOverlap)

    const url = `/upload/batch?${params.toString()}`
    // 使用独立的 axios 以设置 multipart 头
    const instance = axios.create({ baseURL: '/api', timeout: 300000 })
    const res = await instance.post(url, formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    return res.data
  },

  // 文档：获取分块（分页）
  async getDocumentChunks(docId, page = 1, pageSize = 50) {
    return await api.get(`/documents/${docId}/chunks`, { params: { page, page_size: pageSize } })
  },

  // 文档：详情
  async getDocument(docId) {
    return await api.get(`/documents/${docId}`)
  },

  // 文档：更新名称
  async updateDocumentName(docId, newName) {
    return await api.patch(`/documents/${docId}`, { doc_name: newName })
  },

  // 文档：启用/禁用
  async updateDocumentEnabled(docId, enabled) {
    return await api.patch(`/documents/${docId}`, { is_enabled: !!enabled })
  },

  // 文档：删除
  async deleteDocument(docId) {
    return await api.delete(`/documents/${docId}`)
  },

  // 分块：更新内容
  async updateChunk(docId, chunkIndex, newText) {
    return await api.patch(`/documents/${docId}/chunks/${chunkIndex}`, { chunk_text: newText })
  },

  // 分块：删除
  async deleteChunk(docId, chunkIndex) {
    return await api.delete(`/documents/${docId}/chunks/${chunkIndex}`)
  },

  // 分块：新增
  async createChunk(docId, text) {
    return await api.post(`/documents/${docId}/chunks`, { chunk_text: text })
  }
}

// 处理流式响应的工具函数
export function handleStreamResponse(response, onMessage, onComplete, onError) {
  const reader = response.body.getReader()
  const decoder = new TextDecoder()
  let buffer = ''

  function read() {
    reader.read().then(({ done, value }) => {
      if (done) {
        onComplete()
        return
      }

      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''

      for (const line of lines) {
        if (line.trim() === '') continue
        if (line.startsWith('data: ')) {
          const data = line.slice(6)
          if (data === '[DONE]') {
            onComplete()
            return
          }
          try {
            const parsed = JSON.parse(data)
            onMessage(parsed)
          } catch (e) {
            console.error('解析SSE数据失败:', e)
            onError(e)
          }
        }
      }

      read()
    }).catch(error => {
      console.error('读取流失败:', error)
      onError(error)
    })
  }

  read()
}

export default apiService